package net.qhzw.vip.qiyu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.qhzw.vip.qiyu.entity.GuaranteeSite;
import net.qhzw.vip.qiyu.entity.SysUser;
import net.qhzw.vip.qiyu.mapper.GuaranteeSiteMapper;
import net.qhzw.vip.qiyu.model.*;
import net.qhzw.vip.qiyu.service.DtsBarManageService;
import net.qhzw.vip.qiyu.service.GuaranteeCompanyService;
import net.qhzw.vip.qiyu.service.GuaranteeSiteService;
import net.qhzw.vip.qiyu.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import net.qhzw.vip.qiyu.util.SecurityUtils;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class GuaranteeSiteServiceImpl extends ServiceImpl<GuaranteeSiteMapper, GuaranteeSite> implements GuaranteeSiteService {

    @Autowired
    private GuaranteeCompanyService guaranteeCompanyService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private GuaranteeSiteMapper guaranteeSiteMapper;
    @Autowired
    private DtsBarManageService dtsBarManageService;



    @Override
    public Page<GuaranteeSite> findByPage(Page<GuaranteeSite> page, Long shopId, String name, Byte status) {
        Long userId = SecurityUtils.getUserId();
        SysUser sysUser = sysUserService.getById(userId);
        Long companyId = sysUser.getCompanyId();
        if (companyId == 1L) {
            companyId = null;
        }
        page.addOrder(OrderItem.desc("created"));
        Page<GuaranteeSite> guaranteeSitePage = page(page, new LambdaQueryWrapper<GuaranteeSite>()
                .eq(shopId != 1, GuaranteeSite::getShopId, shopId)
                .eq(companyId != null, GuaranteeSite::getCompanyId, companyId)
                .eq(status != null, GuaranteeSite::getStatus, status)
                .eq(!StringUtils.isEmpty(name), GuaranteeSite::getName, name));
        List<GuaranteeSite> records = guaranteeSitePage.getRecords();
        if (!CollectionUtils.isEmpty(records)) {
            for (GuaranteeSite record : records) {
                if (record.getCompanyId() != null) {
                    String companyName = guaranteeCompanyService.getNameById(record.getCompanyId());
                    record.setCompanyName(companyName);
                }
            }
        }
        return guaranteeSitePage;
    }

    /**
     * 根据id查询名称
     *
     * @param siteId
     * @return
     */
    @Override
    public String findNameById(Long siteId) {
        GuaranteeSite guaranteeSite = getById(siteId);
        if (guaranteeSite != null) {
            return guaranteeSite.getName();
        }
        return null;
    }

    /***
     * 根据担保公司id获取站点id
     * @param companyId
     * @return
     */
    @Override
    public List<Long> getSiteIds(Long companyId) {
        List<Long> result = new ArrayList<>();
        List<GuaranteeSite> siteList = list(new LambdaQueryWrapper<GuaranteeSite>()
                .eq(companyId != null, GuaranteeSite::getCompanyId, companyId));
        if (!CollectionUtils.isEmpty(siteList)) {
            for (GuaranteeSite guaranteeSite : siteList) {
                result.add(guaranteeSite.getId());
            }
        }
        return result;
    }

    /***
     * 获取担保站点
     * @param idCard
     * @return
     */
    @Override
    public GuaranteeSite getGuaranteeSiteByUserId(String idCard) {
        return guaranteeSiteMapper.findGuaranteeSiteByUserId(idCard);
    }

    /**
     * 查询担保站点风险预警
     *
     * @param query
     * @return
     */
    @Override
    public List<SysWarningVo> getWarning(WarningQuery query) {
        query.setWarrantyStatus((byte) 1);
        return guaranteeSiteMapper.getWarning(query);
    }

    @Override
    public int getWarningCount(WarningQuery query) {
        query.setWarrantyStatus((byte) 1);
        return guaranteeSiteMapper.getWarningCount(query);
    }


    /***
     * 根据担保公司查询站点
     * @param companyId
     * @return
     */
    @Override
    public List<GuaranteeSite> getByCompanyId(Long companyId) {
        List<GuaranteeSite> guaranteeSites = guaranteeSiteMapper.selectList(new LambdaQueryWrapper<GuaranteeSite>()
                .eq(GuaranteeSite::getCompanyId, companyId));
        return guaranteeSites;
    }

    /**
     * 根据身份证号查询担保公司 站点
     *
     * @param idCards
     * @return
     */
    @Override
    public List<GuaranteeSiteUser> findByIdCards(List<String> idCards) {
        if (CollectionUtils.isEmpty(idCards)) {
            return new ArrayList<GuaranteeSiteUser>();
        }
        return guaranteeSiteMapper.findByIdCards(idCards);
    }

    /***
     * 根据userId查询站点ID
     * @param userId
     * @return
     */
    @Override
    public List<Long> getSiteIdByUserId(Long userId) {
        List<Long> siteIdByUserId = guaranteeSiteMapper.getSiteIdByUserId(userId);
        if (CollectionUtils.isEmpty(siteIdByUserId)) {
            List<Long> collect = siteIdByUserId.stream().distinct().collect(Collectors.toList());
            return collect;
        }
        return siteIdByUserId;
    }

    /***
     * 查询骑遇站点风险预警
     * @param amount
     * @return
     */
    @Override
    public int riskWarningQYCount(BigDecimal amount, Long shopId) {
        return guaranteeSiteMapper.riskWarningQYCount(amount, shopId);
    }


    /***
     * 根据担保人员查询担保公司站点
     * @param id
     * @return
     */
    @Override
    public GuaranteeSiteUser getName(Long id) {
        return guaranteeSiteMapper.getName(id);
    }

    /**
     * 根据担保人员查询租车站点电话
     *
     * @param id
     * @return
     */
    @Override
    public Long findSiteMobile(Long id) {
        return guaranteeSiteMapper.findSiteMobile(id);
    }

    /**
     * 查询各站点换车退车租车量
     */
    @Transactional
    @Override
    public List<BigDataInfo> getCarStatistics(String id) {

        List<BigDataInfoFask> bigDataInfoFasks = guaranteeSiteMapper.selectAllFakeData();
        List<BigDataInfo> list = new ArrayList<>();
        // 1代表日  0代表近总的
        if (id != null && id.equals("1")) {
            if (bigDataInfoFasks.get(1).getIsFake() == 1) {
                for (BigDataInfoFask bigDataInfoFask : bigDataInfoFasks) {
                    BigDataInfo bigDataInfo = new BigDataInfo();
                    if (bigDataInfoFask.getIsFake() == 1 && bigDataInfoFask.getIsFake() != null && bigDataInfoFask.getName() != null) {
                        bigDataInfo.setName(bigDataInfoFask.getName());
                        bigDataInfo.setNumOfCarRentalAmt(bigDataInfoFask.getNumOfCarRentalAmt() * new Random().nextInt(10)+1);
                        bigDataInfo.setRetAmtOfCarNum(bigDataInfoFask.getRetAmtOfCarNum() * new Random().nextInt(10)+1);
                        list.add(bigDataInfo);
                    }

                }
                return list;
            }
            List<BigDataInfo> carStatistics = guaranteeSiteMapper.getCarStatistics();
            return filterData(carStatistics);
        }else {
            if (bigDataInfoFasks.get(1).getIsFake() == 1) {
                for (BigDataInfoFask bigDataInfoFask : bigDataInfoFasks) {
                    BigDataInfo bigDataInfo = new BigDataInfo();
                    if (bigDataInfoFask.getIsFake() == 1  && bigDataInfoFask.getName() != null && bigDataInfoFask.getRetAmtOfCarNum() != null && bigDataInfoFask.getAmtXferNum() != null && bigDataInfoFask.getRetAmtOfCarNum() >0 ) {
                        bigDataInfo.setName(bigDataInfoFask.getName());
                        bigDataInfo.setNumOfCarRentalAmt(bigDataInfoFask.getNumOfCarRentalAmt() * new Random().nextInt(8)+1 +500);
                        bigDataInfo.setRetAmtOfCarNum(bigDataInfoFask.getRetAmtOfCarNum()+ new Random().nextInt(4)+1);
                        bigDataInfo.setAmtXferNum(bigDataInfoFask.getAmtXferNum()+ new Random().nextInt(3)+1);
                        list.add(bigDataInfo);

                    }

                }
                 saveLeaseCar(list);
                return list;
            }
            List<BigDataInfo> carStatisticsByMothon = guaranteeSiteMapper.getCarStatisticsByMothon();
            return filterData(carStatisticsByMothon);
        }

    }

    private void saveLeaseCar(List<BigDataInfo> list) {

        int sum = list.stream().mapToInt(BigDataInfo::getNumOfCarRentalAmt).sum();
        int sum1 = list.stream().mapToInt(BigDataInfo::getRetAmtOfCarNum).sum();
        int sum2 = list.stream().mapToInt(BigDataInfo::getAmtXferNum).sum();
        guaranteeSiteMapper.updateIsFakerTodayLease(sum,sum1,sum2);

    }

    public List<BigDataInfo> filterData(List<BigDataInfo> list){
        List<BigDataInfo> collect = list.stream()
                .filter(bigDataInfo -> (bigDataInfo.getNumOfCarRentalAmt()+bigDataInfo.getAmtXferNum()+bigDataInfo.getRetAmtOfCarNum())> 0)
                .collect(Collectors.toList());
        return collect;

    }
    /**
     * 查询各站点换车退车租车量  近30天
     */
    //@Override
    //public List<BigDataInfo> getCarStatisticsByMothon() {
    //    return guaranteeSiteMapper.getCarStatisticsByMothon();
    //}
    //public static void main(String[] args) {
    //    int i = new Random().nextInt(10);
    //    System.out.println(i+1);
    //}

    /**
     * 查询各站点租车 换车 退车营业额
     */
    @Override
    @Transactional
    public List<BigDataInfo> getTheSiteTurnover() {
        List<BigDataInfoFask> bigDataInfoFasks = guaranteeSiteMapper.selectAllFakeData();
        List<BigDataInfo> list = new ArrayList<>();
        DecimalFormat df1=  new DecimalFormat("#.00");
        if (bigDataInfoFasks.get(1).getIsFake() == 1) {
            for (BigDataInfoFask bigDataInfoFask : bigDataInfoFasks) {
                BigDataInfo bigDataInfo = new BigDataInfo();
                if (bigDataInfoFask.getIsFake() == 1 && bigDataInfoFask.getName() != null && bigDataInfoFask.getTodayTentalRev()!=null) {
                    bigDataInfo.setName(bigDataInfoFask.getName());
                    bigDataInfo.setTodayTentalRev(String.valueOf(df1.format(Float.parseFloat(bigDataInfoFask.getTodayTentalRev()) * new Random().nextInt(5)+1)));
                    //bigDataInfo.setNumOfCarRentalAmt(bigDataInfoFask.getNumOfCarRentalAmt());
                    //bigDataInfo.setRetAmtOfCarNum(bigDataInfoFask.getRetAmtOfCarNum());
                    //bigDataInfo.setAmtXferNum(bigDataInfoFask.getAmtXferNum());
                    list.add(bigDataInfo);

                }
            }
           String todayMll =  getTentalRev(list);
             guaranteeSiteMapper.updateIsFakerToday(todayMll);
            return list;
        }
        return guaranteeSiteMapper.getTheSiteTurnover();
    }

    private String getTentalRev(List<BigDataInfo> list) {

        double sum = list.stream().map(BigDataInfo::getTodayTentalRev).mapToDouble(Double::parseDouble).sum();
        return String.valueOf(sum);

    }

    /**
     * 商城经销商前15销售额排名图
     * @return
     */
    @Override
    public List<BigDataInfo> getMallshoping() {
        return guaranteeSiteMapper.getMallshoping();

      }

    // 获取当前时间的前5个月
    public List<String> getLast12Months() {
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        List<String> list = new ArrayList<>();
        for(int i = 0; i < 5; i++){
            cal.add(Calendar.MONTH, -1);//每次减少1个月
            Date d = cal.getTime();//把当前日期转换成时间格式
            String dateStr = sdf.format(d);//将时间格式化成带年月的字符串
            System.out.println(dateStr);
           list.add(dateStr);
        }
        return list;
    }

    @Override
    public List<BigDataInfo> getMallshopingTotal() {
        List<String> months = getLast12Months();
        List<BigDataInfoFask> bigDataInfoFasks = guaranteeSiteMapper.selectAllFakeData();
        List<BigDataInfo> list = new ArrayList<>();
        if (bigDataInfoFasks.get(1).getIsFake() == 1 ) {
            int i = 0;
            //for (int i = 0; i < bigDataInfoFasks.size(); i++) {
            //    BigDataInfo bigDataInfo = new BigDataInfo();
            //    if (bigDataInfoFasks.get(i).getIsFake() == 1 && bigDataInfoFasks.get(i).getMonths() != null) {
            //        bigDataInfo.setMonths(months.get(i1));
            //        bigDataInfo.setTot(bigDataInfoFasks.get(i).getTot() * new Random().nextInt(10)+1);
            //        list.add(bigDataInfo);
            //        i1 ++;
            //    }
            //}
            for (BigDataInfoFask bigDataInfoFask : bigDataInfoFasks) {

                BigDataInfo bigDataInfo = new BigDataInfo();
                if (bigDataInfoFask.getIsFake() == 1 && bigDataInfoFask.getMonths() != null) {
                    bigDataInfo.setMonths(months.get(i));
                    bigDataInfo.setTot(bigDataInfoFask.getTot() * new Random().nextInt(10)+1);
                    list.add(bigDataInfo);
                    i+=1;
                }
            }
            return list;
        }
        return guaranteeSiteMapper.getMallshopingTotal();
    }

    /**
     * 收入指标统计
     * @return
     */
    @Override
    public String getIncmIdxStatistics() {
        String incmIdxStatistics = guaranteeSiteMapper.getIncmIdxStatistics();
        return incmIdxStatistics;
    }
    public BigDecimal getIncmIdxStat() {
        String incmIdxStatistics = guaranteeSiteMapper.getIncmIdxStatistics();
        return new BigDecimal(incmIdxStatistics).abs();
    }

    /**
     *骑遇小遇 租车业务 商城业务 维修业务综合统计
     * @return
     */
    @Override
    public Map<String, Integer> getComprehensiveStatistics() {
        return guaranteeSiteMapper.getComprehensiveStatistics();
    }
    /**
     * 维修救援 维修师傅指标统计
     * @return
     */
    @Override
    public List<BigDataInfo> getMaintIdxStatistics() {
        List<BigDataInfoFask> bigDataInfoFasks = guaranteeSiteMapper.selectAllFakeData();
        List<BigDataInfo> list = new ArrayList<>();
        if (bigDataInfoFasks.get(1).getIsFake() == 1) {
            for (BigDataInfoFask bigDataInfoFask : bigDataInfoFasks) {
                BigDataInfo bigDataInfo = new BigDataInfo();
                if (bigDataInfoFask.getIsFake() == 1 && bigDataInfoFask.getRealName()!=null && bigDataInfoFask.getTechnologyEvaluation() != null) {
                    bigDataInfo.setRealName(bigDataInfoFask.getRealName());
                    bigDataInfo.setServEvaluation(String.valueOf(new Random().nextInt(5)+1));
                    bigDataInfo.setTechnologyEvaluation(String.valueOf(new Random().nextInt(5)+1));
                    bigDataInfo.setSpeedEvaluation(String.valueOf(new Random().nextInt(5)+1));
                    list.add(bigDataInfo);

                }
            }
            return list;
        }
        return guaranteeSiteMapper.getMaintIdxStatistics();
    }



    /**
     * 商户租车业务指标统计
     * @return
     */
    @Override
    public List<BigDataInfo> getBusCarRentalBusStatistics() {
      //Config config=  configMapper.select()
      //  if(config.getisFake()===1){
      //      List
      //              Math.random()*1000
      //
      //
      //                      ret
      //  }
        return guaranteeSiteMapper.getCarMerchantsToRentACarTotal();
    }

    /**
     * 担保公司维度统计
     * @return
     */
    @Override
    public List<BigDataInfo> getGuarCoDimensionStatistics() {
        List<BigDataInfoFask> bigDataInfoFasks = guaranteeSiteMapper.selectAllFakeData();
        List<BigDataInfo> list = new ArrayList<>();
        if (bigDataInfoFasks.get(1).getIsFake() == 1) {
            for (BigDataInfoFask bigDataInfoFask : bigDataInfoFasks) {
                BigDataInfo bigDataInfo = new BigDataInfo();
                if (bigDataInfoFask.getIsFake() == 1 && bigDataInfoFask.getGuaranteeCompanyName()!=null && bigDataInfoFask.getSummation() != null) {
                    bigDataInfo.setGuaranteeCompanyName(bigDataInfoFask.getGuaranteeCompanyName());
                    bigDataInfo.setSummation(bigDataInfoFask.getSummation() * new Random().nextInt(1+10)+1);

                    list.add(bigDataInfo);

                }
            }
            return list;
        }
        return guaranteeSiteMapper.getGuaranteeCompanyDimension();
    }

    @Override
    public String getMallTotalMoney() {
        BigDataInfoFaskModel foundationData = guaranteeSiteMapper.getFoundationData();
        //List<BigDataInfoFask> bigDataInfoFasks = guaranteeSiteMapper.selectAllFakeData();
        //List<BigDataInfoFask> collect = bigDataInfoFasks.stream()
        //        .filter(i -> i.getTodayTentalRev() != null)
        //        .collect(Collectors.toList());
        //// 收集bigDataInfoFasks 中 TodayTentalRev 的和
        //double sum = collect.stream()
        //        .map(BigDataInfoFask::getTodayTentalRev)
        //        .mapToDouble(Double::parseDouble)
        //        .sum();
        ////.mapToObj(BigDecimal::valueOf)
        //        //.reduce(BigDecimal.ZERO, BigDecimal::add);
        if (foundationData != null && foundationData.getIsFake() == 1 && foundationData.getRentTheuser()!= null){
        //    //return (((Math.random() * 10) * 10) + 200)));
        //    DecimalFormat df = new DecimalFormat("0.00");
        //    Double i  = (new Random().nextInt(1+10)+1) * 23.78;
        //df.format(sum * (new Random().nextInt(5)+1))

            return foundationData.getTodayMall();
        }
        return guaranteeSiteMapper.getMallTotalMoney();
    }

    @Override
    public String getInRentTheUser() {
        //List<BigDataInfoFask> bigDataInfoFasks = guaranteeSiteMapper.selectAllFakeData();
        BigDataInfoFaskModel foundationData = guaranteeSiteMapper.getFoundationData();
        if (foundationData != null && foundationData.getIsFake() == 1 && foundationData.getRentTheuser()!= null){
            //return (((Math.random() * 10) * 10) + 200)));
            //return String.valueOf((new Random().nextInt(5)+1) * foundationData.getRentTheuser());
            return foundationData.getInLease();
        }

        return guaranteeSiteMapper.getInRentTheUser();
    }

    @Override
    public List<BigDataInfo> getNowunder() {
        return guaranteeSiteMapper.getNowunder();
    }

    @Override
    public List<BigDataInfo> getBarCount() {

        BigDataInfoFaskModel foundationData = guaranteeSiteMapper.getFoundationData();
        List<BigDataInfo> list = new ArrayList<>();
        if (foundationData.getIsFake() == 1) {
        //    for (BigDataInfoFask bigDataInfoFask : bigDataInfoFasks) {
                BigDataInfo bigDataInfo = new BigDataInfo();
                if ( foundationData.getTote() != null && foundationData.getTote() > 0 && foundationData.getFailures() != 0) {

                    bigDataInfo.setTote(foundationData.getTote());
                    bigDataInfo.setFailures(foundationData.getFailures() * (new Random().nextInt(4)+1));

                    bigDataInfo.setHitchhe(String.valueOf(foundationData.getHitchhe() * (new Random().nextInt(4)+1)));
                    bigDataInfo.setProhibithe(String.valueOf(foundationData.getProhibithe() * (new Random().nextInt(4)+1)));
                    bigDataInfo.setBackNum(String.valueOf(foundationData.getBackNum()* (new Random().nextInt(4)+1)));
                    bigDataInfo.setRecoveryNum(foundationData.getRecoveryNum() * (new Random().nextInt(4)+1));
                    bigDataInfo.setFailureNum(foundationData.getFailureNum() * (new Random().nextInt(4)+1));
                    DecimalFormat df = new DecimalFormat("0.00");
                    bigDataInfo.setFailurePercentage(String.valueOf(df.format(((Double.parseDouble(foundationData.getFailurePercentage().replace("%",""))/100) * (new Random().nextInt(4)+1)) * 100))  + "%");
                    bigDataInfo.setRecoveryPercentage(String.valueOf( df.format(((Double.parseDouble(foundationData.getRecoveryPercentage().replace("%",""))/100) * (new Random().nextInt(4)+1))* 100)) + "%");
                    bigDataInfo.setBackLv(String.valueOf( df.format(((Double.parseDouble(foundationData.getBackLv().replace("%",""))/100)* (new Random().nextInt(4)+1))* 100)) + "%");

                    bigDataInfo.setFailure(String.valueOf(df.format(((Double.parseDouble(foundationData.getFailure().replace("%",""))/100)  * (new Random().nextInt(4)+1))* 100)) + "%");
                    bigDataInfo.setRecovery(String.valueOf(df.format(((Double.parseDouble(foundationData.getRecovery().replace("%",""))/100) * (new Random().nextInt(4)+1))* 100)) + "%");
                    bigDataInfo.setFailureRate(String.valueOf( df.format(((Double.parseDouble(foundationData.getFailureRate().replace("%",""))/100) * (new Random().nextInt(2)+1))* 100)) + "%");
                    bigDataInfo.setRecoveryRate(String.valueOf(df.format(((Double.parseDouble(foundationData.getRecoveryRate().replace("%",""))/100) * (new Random().nextInt(2)+1))* 100)) + "%");
                    bigDataInfo.setRentTheusers(String.valueOf((Float.parseFloat(foundationData.getRentTheusers()) * (new Random().nextInt(4)+1))));

                    list.add(bigDataInfo);


            }
            return list;
        }
       return dtsBarManageService.getCountFailureRt();

    }

    @Override
    public BigDataInfoFaskModel getallFask() {
        BigDataInfoFaskModel foundationData = guaranteeSiteMapper.getFoundationData();
        List<BigDataInfoFask> bigDataInfoFasks = guaranteeSiteMapper.selectAllFakeData();
        foundationData.setBigDataInfoFasks(bigDataInfoFasks);
        return foundationData;
    }

    @Override
    public boolean updateIsFaker(String isFaker) {
        if (isFaker.equals("1")){
            guaranteeSiteMapper.updateIsFaker();
            boolean b = guaranteeSiteMapper.updateIsFakerSon();
            return b;
        }else {
            guaranteeSiteMapper.updateIsFakerSon1();
            boolean b = guaranteeSiteMapper.updateIsFaker1();
            return b;
        }

    }
}
